package com.teamc.team.controller;

import com.teamc.team.service.IUserService;
import com.teamc.team.util.VerifyCodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author ding
 */
@Controller
public class RegisterController {
    /**
     * 注册控制
     */
    private final IUserService userService;
    /**
     * 验证码
     * */
    private final VerifyCodeUtil util;

    public RegisterController(IUserService userService, VerifyCodeUtil util) {
        this.userService = userService;
        this.util = util;
    }

    @GetMapping("getVerImg")
    public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedImage image = util.getImage();
        String text = util.getText();
        HttpSession session = req.getSession();
        session.setAttribute("index_code", text);
        resp.setContentType("image/jpeg");
        VerifyCodeUtil.output(image, resp.getOutputStream());
    }

    @RequestMapping({"/register","/register.html"})
    public String login() {
        return "/register";
    }

    /**
     * 注册的主方法
     * @param username
     * @param password
     * @param password2
     * @param code
     * @param request
     * @param mo
     * @return
     */
    @PostMapping("/reg")
    @ResponseBody
    public String register(@RequestParam("username")String username, @RequestParam("password")String password,
                           @RequestParam("password2")String password2,
                           @RequestParam("verifyCode")String code,
                           HttpServletRequest request, HttpServletResponse response, Model mo) throws ServletException, IOException {
        String regex = "^[a-zA-Z]([-_a-zA-Z0-9]{6,20})$";
        if (code.toLowerCase().equals((request.getSession().getAttribute("index_code")).toString().toLowerCase())) {
            if (username.matches(regex) && password.equals(password2)) {
                userService.register(username,password);
                return "注册成功！您的账户为："+username+" 请返回首页登录！";
            } else {
                return "用户名/密码格式错误！";
            }
        }
        return "验证码错误！";
    }

    /**
     * ajax动态检测是否注册
     * @return
     */
    @RequestMapping("/isRegister")
    @ResponseBody
    public String isLogin(@RequestParam("username") String userName) {
        String regex = "^[a-zA-Z]([-_a-zA-Z0-9]{6,20})$";
        if (!userName.matches(regex)){
            return "2";
        }
        if (userService.isRegister(userName)) {
            return "1";
        }
        return "0";
    }
}
